/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.bangcommunity.bbframe.sdm.web.shiro.realm;

import com.bangcommunity.bbframe.common.utils.lang.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;

public abstract class AbstractSdmShiroRealm<PK extends Serializable, TK> extends AuthorizingRealm {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 认证回调函数,登录时调用.
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
            throws AuthenticationException {
        TK token = (TK) authcToken;
        if (null == token) {
            logger.error("no token when login");
            throw new AuthenticationException("用户名密码有误");
        }
        /**
         * dologin getuserinfo set shirouser
         */
        logger.debug("start login token={} ", token);
        IShiroUser<PK> shiroUser = this.retriveFromToken(token);
        if (null != shiroUser && StringUtils.isNotBlank(shiroUser.getToken())) {
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(shiroUser,
                    shiroUser.getToken(), shiroUser.getToken());
            return simpleAuthenticationInfo;
        } else {
            logger.error("login fail: authcToken={}", authcToken);
            return null;
        }
    }

    protected abstract IShiroUser<PK> retriveFromToken(TK token);

    /**
     * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }
}
